﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;

namespace Turtle8
{
    public partial class TahasukaCard : UserControl, IMofa
    {
        private event ZimunimModifiedHandler EventZimunimModified;

        PictureBox picBox = new System.Windows.Forms.PictureBox();
        TahasukaNewPanel mainNewPanel;
        ZimunimCard preZimunimCard;
        TahasukaWorkingRequestCard preWorkingRequestCard;
        TahasukaAlalCard preAlalCard;
        TahasukaSiurKavCard preSiurKavCard;
        YamamTrackCard duringYamamTrackCard;
        TahasukaOpenOldCard mainOldCard;
        LekachimCard postLekachimCard;
        TahasukaDuringPostCard duringPostCard;

        IList<string> armyIDList = new List<string>();
        string tableName = "TahasukaZimunim";
        DateTime startDate;
        DateTime endDate;
        string mofaStr = "tahasuka";
        public bool IsOpen { get; set; }

        #region Properties
        public IList<string> ArmyIDList
        { get{   return armyIDList; }}

        public DateTime StartDate
        { 
            get{ return startDate;}
            set {startDate = value;}
        }

        public DateTime EndDate
        {
            get{return endDate;}
            set{endDate = value;}
        }

        public string TableName
        { get{return tableName;} }

        public string MofaString
        {get{return mofaStr;} }
        #endregion
        public TahasukaCard()
        {

            InitializeComponent();
            initTahasuka();
            picBox.AccessibleName = "מסך ראשי";

            this.Dock = DockStyle.Fill;
        }

        //those functions are responsible of remove and add the just selected UserControl 
        private void changeMainPanel(Control ctrl)
        {
            if(!splitContainer.Panel2.Contains(ctrl))
            {
                tabControl.SelectedIndex = 1;
                this.splitContainer.Panel2.Controls.Clear();
                this.splitContainer.Panel2.Controls.Add(ctrl);
                tabControl.SelectedIndex = 0;
            }
            textBoxHeader.Text = "כרטיס תעסוקה - " + ctrl.AccessibleName;
        }
        public void changeMainPanel(){ changeMainPanel(picBox); }
        public void changeDuringTabPanel(Control ctrl)
        {
            if (!duringSplitContainer.Panel2.Contains(ctrl))
            {
                this.duringSplitContainer.Panel2.Controls.Clear();
                this.duringSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס תעסוקה - " + ctrl.AccessibleName;
        }
        public void changePreTabPanel(Control ctrl)
        {
            if (!preSplitContainer.Panel2.Contains(ctrl))
            {
                this.preSplitContainer.Panel2.Controls.Clear();
                this.preSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס תעסוקה - " + ctrl.AccessibleName;
        }
        public void changePostTabPanel(Control ctrl)
        {
            if (!postSplitContainer.Panel2.Contains(ctrl))
            {
                this.postSplitContainer.Panel2.Controls.Clear();
                this.postSplitContainer.Panel2.Controls.Add(ctrl);
            }
            textBoxHeader.Text = "כרטיס תעסוקה - " + ctrl.AccessibleName;
        }


        //pre-Tahasuka cards Button_Click handlers
        private void buttonZimunimTrack_Click(object sender, EventArgs e) { changePreTabPanel(preZimunimCard); }
        private void buttonWorkRequests_Click(object sender, EventArgs e) { changePreTabPanel(preWorkingRequestCard); }
        private void buttonSiurKav_Click(object sender, EventArgs e)      { changePreTabPanel(preSiurKavCard); }    
        private void buttonAlal_Click(object sender, EventArgs e)  
        {
            changePreTabPanel(preAlalCard);
            preAlalCard.refresh();
        }


        //during-Tahasuka cards Button_Click handlers
        private void buttonTahasukaWorkTrack_Click(object sender, EventArgs e) { changeDuringTabPanel(duringYamamTrackCard); }
        private void buttonPostCard_Click(object sender, EventArgs e) { changeDuringTabPanel(duringPostCard); }


        //post-Tahasuka cards Button_Click handlers
        private void buttonLekachim_Click(object sender, EventArgs e)
        {
            changePostTabPanel(postLekachimCard);
        }

        //Tahasuka Main events
        private void TahasukaUserControl_Load(object sender, EventArgs e)
        {
            picBox.SizeMode = PictureBoxSizeMode.StretchImage;
            String currentDir = System.IO.Directory.GetCurrentDirectory();
            picBox.Image = Image.FromFile(CompanyManager.StartupPath + @"\images\Pillbox.jpg");
            picBox.Dock = DockStyle.Fill;
            changeMainPanel(picBox);
        }
        private void buttonNewTahasuka_Click(object sender, EventArgs e)
        {
            //case there is an open Tahasuka already
           if (!IsOpen)
           {
               if (mainNewPanel == null)
                   mainNewPanel = new TahasukaNewPanel(this);
               changeMainPanel(mainNewPanel);
           }
           else MessageBox.Show(".ישנו כרטיס תעסוקה פתוח כרגע. לא ניתן לנהל יותר מתעסוקה אחת בו זמנית");
        }
        
        private void buttonOpenCurrent_Click(object sender, EventArgs e)
        {
            if (!IsOpen)
                MessageBox.Show(".אין כרגע כרטיס תעסוקה פתוח");
            else
            {
                changeMainPanel(tabControl);
                buttonZimunimTrack_Click(sender, e);
            }
        }
        private void buttonOpenOld_Click(object sender, EventArgs e) {/* changeMainPanel(mainOldCard); */}
      
        public int getTotalDays()
        {
            DateTime start = StartDate;
            DateTime end = endDate;

            return (int)(end.Subtract(start).Days + 1);
        }

        public void deleteAllSoldierRequests(string armyID)
        {
            string deleteStr = "DELETE FROM [TahasukaRequests] WHERE startDate=@startDate AND armyID=@armyID";
            SqlCommand deleteCommand = new SqlCommand(deleteStr, CompanyManager.Connection);
            deleteCommand.Parameters.Add("@armyID", SqlDbType.NVarChar).Value = armyID;
            deleteCommand.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
            deleteCommand.ExecuteNonQuery();
        }

        public void deleteRequests(BaseCollection row_col, int armyID_index)
        {
            SqlDataAdapter da;
            da = preWorkingRequestCard.SqlDataAdapter;
            //this part handles TahasukaRequestsZimunim
            foreach (DataGridViewRow row in row_col)
            {
                da.DeleteCommand.Parameters["@requestID"].Value = row.Cells["requestID"].Value;
                da.DeleteCommand.ExecuteNonQuery();
            }
        }

        public void deleteSoldierFromMofa(DataGridViewSelectedRowCollection row_col, int col_index)
        {
            SqlDataAdapter da;
            if (row_col.Count > 0)
            { 
                da = preZimunimCard.SqlDataAdapter;
                deleteSoldierFromMofa(row_col, da);
                da = preAlalCard.SqlDataAdapter;
                deleteSoldierFromMofa(row_col, da);
                da = duringYamamTrackCard.SqlDataAdapter;
                deleteSoldierFromMofa(row_col, da);
            }
            EventZimunimModified(this, new EventArgs());
        }

        private void deleteSoldierFromMofa(BaseCollection row_col, SqlDataAdapter da)
        {
            da.DeleteCommand.Parameters["@startDate"].Value = startDate;

            // for each soldier, inserts a row per each day in 'mofa'
            foreach (DataGridViewRow row in row_col)
            {
                da.DeleteCommand.Parameters["@armyID"].Value = (String)(row.Cells["armyID"].Value);
                da.DeleteCommand.ExecuteNonQuery();
            }  
        }
        public void addSoldiersToMofa()
        {
            SqlDataAdapter da;
            if (ArmyIDList.Count > 0)
            {
                //adding rows to table: [Yamam]
                da = duringYamamTrackCard.SqlDataAdapter;
                da.InsertCommand.Parameters["@startDate"].Value = startDate;

                // for each soldier, inserts a row per each day in 'mofa'
                foreach (string army_id in ArmyIDList)
                {
                    da.InsertCommand.Parameters["@armyID"].Value = army_id;
                    for (int i = 0; i < getTotalDays(); i++)
                    {
                        da.InsertCommand.Parameters["@date"].Value = startDate.AddDays(i);
                        CompanyManager.insertSqlQuery(da.InsertCommand);
                    }
                }

                //adding rows to table: [TahasukaZimunim] 
                da = preZimunimCard.SqlDataAdapter;         
                da.InsertCommand.Parameters["@startDate"].Value = startDate;

                // for each soldier, inserts a row per each day in 'mofa'
                foreach (string army_id in ArmyIDList)
                {
                    da.InsertCommand.Parameters["@armyID"].Value = army_id;
                    CompanyManager.insertSqlQuery(da.InsertCommand);
                }
                //adding rows to table: [TahasukaAlal]
                da = preAlalCard.SqlDataAdapter;
                da.InsertCommand.Parameters["@startDate"].Value = startDate;

                // for each soldier, inserts a row per each day in 'mofa'
                foreach (string army_id in ArmyIDList)
                {
                    da.InsertCommand.Parameters["@armyID"].Value = army_id;
                    CompanyManager.insertSqlQuery(da.InsertCommand);
                }

                EventZimunimModified(this, new EventArgs());

            }
        }
        public void addSoldierRequest()
        {
            SqlDataAdapter da;
            //adding rows to table: [TahasukaRequests]
            da = preWorkingRequestCard.SqlDataAdapter;
            da.InsertCommand.Parameters["@startDate"].Value = startDate;
            da.InsertCommand.Parameters["@endDate"].Value = endDate;
            da.InsertCommand.Parameters["@comments"].Value = (string)string.Empty;

            foreach (string str in ArmyIDList)
            {
                da.InsertCommand.Parameters["@armyID"].Value = str;
                CompanyManager.insertSqlQuery(da.InsertCommand);
            }
        }

        private void initTahasuka()
        {
            IsOpen = false;
            SqlCommand selectCmd = new SqlCommand("SELECT * FROM TahasukaData WHERE isClosed = 0", CompanyManager.Connection);
            SqlDataReader reader = selectCmd.ExecuteReader();

            //means there is an open Tahasuka already. we allow only 1 Tahasuka to be open at a time.
            if (reader.Read())
            {
                DateTime dt;
                dt = (DateTime)reader["startDate"];
                startDate = dt;
                dt = (DateTime)reader["endDate"];
                endDate = dt;
                labelTahasukaDetails.Text = (string)reader["location"] + "."
                                           + startDate.ToShortDateString() + "-" + endDate.ToShortDateString(); 
                reader.Close();

                //create all cards in Tahasuka
                mainNewPanel = new TahasukaNewPanel(this);
                preZimunimCard = new ZimunimCard(this);
                duringYamamTrackCard = new YamamTrackCard(this);
                preWorkingRequestCard = new TahasukaWorkingRequestCard(this);
                preAlalCard = new TahasukaAlalCard(this);
                preSiurKavCard = new TahasukaSiurKavCard(this);
                mainOldCard = new TahasukaOpenOldCard();
                postLekachimCard = new LekachimCard(this);
                duringPostCard = new TahasukaDuringPostCard(this);

                setEventZimunimModifiedHandler();

                changePreTabPanel(preZimunimCard);
                changeDuringTabPanel(duringYamamTrackCard);
                changePostTabPanel(postLekachimCard);

                IsOpen = true;
            }
            else
            {
                StartDate = DateTime.MinValue;
                EndDate = DateTime.MinValue;
            }
            reader.Close();
        }
        public void NewTahasukaEvent(object o, EventArgs e)
        {
            initTahasuka();
            changeMainPanel(this.tabControl);
            changePreTabPanel(preZimunimCard);
           
        }

       override public string ToString()
        {
            return "תעסוקה";
        }

       private void setEventZimunimModifiedHandler()
       {
           //this event will fire when there will be modifications in the ZimunimCard (while adding\removing soldiers)
           EventZimunimModified += new ZimunimModifiedHandler(duringYamamTrackCard.refresh);
       }

       private void buttonFinish_Click(object sender, EventArgs e)
       {
           string updateStr = @"UPDATE [TahasukaData] SET isClosed=@isClosed WHERE startDate=@startDate";
           SqlCommand updateCmd = new SqlCommand(updateStr, CompanyManager.Connection);
           updateCmd.Parameters.Add("@isClosed", SqlDbType.Bit).Value = true;
           updateCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = startDate;
           updateCmd.ExecuteNonQuery();
           IsOpen = false;

           preAlalCard = null;
           preSiurKavCard = null;

           preZimunimCard = null;
           preWorkingRequestCard = null;
           duringYamamTrackCard = null;
           mainOldCard = null;
           postLekachimCard = null;
           duringPostCard = null;

           labelTahasukaDetails.Text = string.Empty;
           changeMainPanel();
       }

       private void tabControl_Selecting(object sender, TabControlCancelEventArgs e)
       {
           if (tabControl.SelectedTab.Name.Equals("tabPagePre"))
               changePreTabPanel(preZimunimCard);
           else if (tabControl.SelectedTab.Name.Equals("tabPageDuring"))
               changeDuringTabPanel(duringYamamTrackCard);
           else if (tabControl.SelectedTab.Name.Equals("tabPagePost"))
               changePostTabPanel(postLekachimCard);
       }
    }
}
